package com.ts.api.http.org.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.ts.api.http.org.entity.apply.OrgApplyRongYiTong;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.org.handler.ApiOrgPhoneMd5ConvertHandler;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5Apply;
import com.ts.api.module.api.convert.org.model.RespOrgPhoneMd5DataExchange;

import java.util.Map;

/**
 * 安心分期&融驿通
 * @ Author 江小游
 * @ Date 2025/5/28 20:25
 */
@ApiPlan(productId = "223", type = ApiPlanConvertType.ORG_PHONE_MD5)
public class ApiOrgPhoneMd5RongYiTong implements ApiOrgPhoneMd5ConvertHandler {
    private static final String KEY = "ba573b44f28fbccf";
    private static final String IV = "0f79048a1470d636";
    private static final String SOURCE_CODE = "99cc80ad462f9441f221e1b991028a86";
    private static final String ACCESS_KEY = "b0b96125-2aa5-4348-b9af-43ec37423b11";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        return MapUtils.newHashMap(newMap -> {
            newMap.put("phone", apiDataExchangeParameter.getPhoneMd5().toLowerCase());
            newMap.put("sourceCode", SOURCE_CODE);
            newMap.put("accessKey", ACCESS_KEY);
        });
    }

    @Override
    public RespOrgPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        //  撞库返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (data == null) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        boolean phoneMd5Exist = data.getBoolean("phoneMd5Exist");
        if (phoneMd5Exist) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("status"), 200)) {
            return RespOrgPhoneMd5DataExchange.ofFail();
        }
        //  根据文档响应判断
        return RespOrgPhoneMd5DataExchange.ofSuc();
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  进件流程-默认JSON发送如果需要别的方式，或者需要增加请求头，请看apiApplyMessage拓展方法
        OrgApplyRongYiTong orgApply = new OrgApplyRongYiTong();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        //  赋值进件属性
        orgApply.setUsername(apiApplyParameter.getUserName());
        orgApply.setPhone(apiApplyParameter.getPhone());
        orgApply.setId_card_num(apiApplyParameter.getIdcard());
        orgApply.setCity(apiApplyParameter.getCity());
        orgApply.setAge(apiFieldConverter.getAgeInt());
        //  进件字段映射
        applyFieldMapping(apiApplyParameter, orgApply);
        // 加密
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(orgApply));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("sourceCode", SOURCE_CODE);
            newMap.put("accessKey", ACCESS_KEY);
            newMap.put("iv", IV);
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespOrgPhoneMd5Apply respApply(String respJson) throws Exception {
        //  进件返回响应体判断
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("status"), 200)) {
            return RespOrgPhoneMd5Apply.ofFail();
        }
        //  根据文档响应判断
        return RespOrgPhoneMd5Apply.ofSuc();
    }

    private void applyFieldMapping(ApiApplyParameter apiApplyParameter, OrgApplyRongYiTong orgApply) {
        //  性别-要获取中文性别（1男/2 女）
        Integer sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", 1)
                .when("1", 2)
                .end();
        orgApply.setSex(sex);
        /* 职业
           0 自由，1 企业主，2 白领，3 公务员
         */
        Integer career = ChooseEq.create(apiApplyParameter.getCareer())
                .when("1", 2)
                .when("2", 0)
                .when("3", 1)
                .when("4", 3)
                .when("5", 0)
                .end();
        orgApply.setJob(career);
        /* 月薪
          1 是 2 否
        */
        Integer monthlySalary = ChooseEq.create(apiApplyParameter.getMonthlySalary())
                .when("1", 1)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 1)
                .end();
        orgApply.setSalary(monthlySalary);
        /*
          公积金
         1 有 2 无
        */
        Integer providentFund = ChooseEq.create(apiApplyParameter.getProvidentFund())
                .when("1", 2)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .end(2);
        orgApply.setGjj(providentFund);
        /*
          房产情况
          1 有 2 无
        */
        Integer realEstateInfo = ChooseEq.create(apiApplyParameter.getRealEstateInfo())
                .when("1", 2)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 1)
                .when("6", 1)
                .end(2);
        orgApply.setHouse(realEstateInfo);
        /*
          车辆情况
          1 有 2 无
         */
        Integer carInfo = ChooseEq.create(apiApplyParameter.getCarInfo())
                .when("1", 2)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .end(2);
        orgApply.setCar(carInfo);
       /*
       保险保单
       1 有 2 无
        */
        Integer insurancePolicy = ChooseEq.create(apiApplyParameter.getInsurancePolicy())
                .when("1", 2)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .end(2);
        orgApply.setInsurance(insurancePolicy);
        /*
          信用卡额度
          1 有 2 无
        */
        Integer creditLimit = ChooseEq.create(apiApplyParameter.getCreditLimit())
                .when("1", 2)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .when("5", 1)
                .when("6", 1)
                .end(2);
        orgApply.setXyk(creditLimit);
        /*
          社保缴纳
          1 有 2 无
        */
        Integer socialSecurity = ChooseEq.create(apiApplyParameter.getSocialSecurity())
                .when("1", 2)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .end(2);
        orgApply.setShebao(socialSecurity);
        // 企业纳税
        orgApply.setPay_tax(2);
        // 微粒贷
        orgApply.setParticles(2);
       /*
          营业执照
          1 有 2 无
       */
        Integer bizLicenseYear = ChooseEq.create(apiApplyParameter.getBizLicenseYear())
                .when("1", 2)
                .when("2", 1)
                .when("3", 1)
                .when("4", 1)
                .end(2);
        orgApply.setBusiness_license(bizLicenseYear);
        /*
           芝麻分
           1.600分以下
           2.600~649分
           3.650~699分
           4.700分以上
         */
        Integer sesameCredit = ChooseEq.create(apiApplyParameter.getSesameCredit())
                .when("1", 600)
                .when("2", 649)
                .when("3", 699)
                .when("4", 750)
                .end(600);
        orgApply.setZhimafen(sesameCredit);
        /*
           贷款金额
           1.3万以下
           2.5万-10万
           3.10万-20万
           4.20万以上
         */
        Integer loanAmount = ChooseEq.create(apiApplyParameter.getLoanAmount())
                .when("1", 30000)
                .when("2", 100000)
                .when("3", 200000)
                .when("4", 300000)
                .end(30000);
        orgApply.setLoan(loanAmount);
        // 备注
        orgApply.setContent(apiApplyParameter.getFormRemark());
    }
}
